/*
 *  Copyright © 2014 CIB Co.Ltd
 *  * All right reserved
 *  * Auther:jin xingwang
 *
 */

package com.jwts.common;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jwts.secret.RsaUtil;
import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.time.LocalDateTime;
import java.util.UUID;

/**
 * 功能
 * @author 靳兴旺
 * @version 1.0.0 2020-7.15
 * jwt实现工具类
 */
public class Jwts {

    private static final Logger logger = LoggerFactory.getLogger(Jwts.class);

    /**
     * 生成token
     * @param header 头部信息
     * @param jwtClaims 内容
     * @return token
     */
    public static String compact(Header header, JwtClaims jwtClaims) {
        String encryptionType = header == null ? "RSA" : header.toString();
        jwtClaims.put("uuid", UUID.randomUUID());
        String signature =dataSignature(header, jwtClaims);
        return  Base64.encodeBase64String(JSONObject.toJSONString(header).getBytes()) + "."
                + Base64.encodeBase64String(JSONObject.toJSONString(jwtClaims).getBytes()) + "."
                + signature;
    }

    /**
     * 签名
     * @param header 头部信息
     * @param jwtClaims 内容
     * @return 签名
     */
    private static String dataSignature(Header header, JwtClaims jwtClaims) {
        String encryptionType = header == null ? "RSA" : header.toString();
        String dataSignature = null;
        if (encryptionType.equals(Header.RSA.name())){
            dataSignature = RsaUtil.encodeByPrivateKey(JSONObject.toJSONString(header) + JSONObject.toJSONString(jwtClaims));
        }
        return dataSignature;
    }

    /**
     * token验证
     * @param tokenString
     * @return 是否正确
     */
    public static Boolean safetyVerification(String tokenString) {
        // 有坑，转义字符
        String[] split = tokenString.split("\\.");

        //jwtClaims中默认的项目数
        int itemCount = 3;
        if (split.length != itemCount) {
            throw new RuntimeException("无效的token");
        }
        // 头部信息
        Header header = JSON.parseObject(Base64.decodeBase64(split[0]), Header.class);
        // 数据信息
        JwtClaims jwtClaims = JSON.parseObject(Base64.decodeBase64(split[1]), JwtClaims.class);
        // 签名信息
        String signature = split[2];
        String failureTimeStr = "failureTime";
        // 验证token是否在有效期内
        if (jwtClaims.get(failureTimeStr) != null) {
            LocalDateTime failureTime = LocalDateTime.parse(jwtClaims.get("failureTime").toString());
            if (LocalDateTime.now().isAfter(failureTime)) {
                throw new RuntimeException("此token已过有效期");
            }
        }
        // 比较签名
        String signatureNew = dataSignature(header, jwtClaims);
        return signature.equals(signatureNew.replaceAll("\r\n",""));
    }
}


